#include<iostream>
#include<unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>

using namespace std;

void signalHandler(int sig)
{
    int n=alarm(5);
    if (n == 0)
    {
        cout << "Alarm was not set." << endl;
    }
    else
    {
        cout << "Alarm was set to go off in " << n << " seconds." << endl;
    }
    cout << "Signal " << sig << " received." << endl;
}

void test1()
{
    signal(SIGINT, signalHandler); //signal(SIGINT, NULL); 空指针等于没有更改处理方式，还是默认动作
    signal(SIGABRT, signalHandler); // 注册SIGABRT信号处理函数
    kill(getpid(), SIGINT); // 发送SIGINT信号给自己
    raise(SIGINT); // 发送SIGINT信号给自己
    abort(); // 触发SIGABRT信号,虽然自定义了SIGABRT的处理函数，但abort()还是会导致程序终止
    while(1)
    {
        cout<<"Running... Press Ctrl+C to send SIGINT." << endl;
        sleep(1);
    }
}

// void alarmcon()
// {
//     int n=alarm(5);
//     while(1)
//     {
//         cout << "Waiting for alarm signal...";
//         if (n == 0)
//         {
//             cout << "Alarm was not set." << endl;
//         }
//         else
//         {
//             cout << "Alarm was set to go off in " << n << " seconds." << endl;
//         }
//         sleep(1);
//     }
// }

void test2()
{
    alarm(5);
    signal(SIGALRM, signalHandler); // 注册SIGALRM信号处理函数
    while(1)
    {
        cout<<"Running... Waiting for SIGALRM." << endl;
        sleep(1);
    }
}

void test3()
{
    pid_t pid = fork();
    if(pid < 0)
    {
        cout << "Fork failed." << endl;
        return;
    }
    else if(pid == 0) // 子进程
    {
        cout<<"Child process started with PID: " << getpid() << endl;
        int a=10;
        a/=0; // 故意制造一个除零错误，触发SIGFPE信号
        exit(2);
    }
    else // 父进程
    {
        int status=0;
        waitpid(pid, &status, 0); // 等待子进程结束
        cout<<"exit_code:"<<((status>>8)&0xFF)<<" exit_signal:"<<(status&0x7F) << " core_dump:"<<((status>>7)&1) << endl;
    }
}
int main()
{
    //test1();
    // test2();
    test3();
    return 0;
}
